<template>
  <div>
    <el-form :model="balanceForm" :rules="balanceFormRoles" ref="balanceForm" label-width="10em">
      <h-box header="重要储值规则（全部必填，保存后不可修改，请谨慎核对后保存）">
        <el-form-item label="储值卡面额" prop="._balance">
          <el-input @change="onChangeBalance" v-model.number="balanceForm._balance" placeholder="请输入" style="width: 240px;">
            <template slot="prepend">面额</template>
            <template slot="append">元</template>
          </el-input>
          <div class="hui-color-text-secondary hui-font-size-small">面额最少 0.01 元，2 位小数以内。建议面额设置为整数，并以桌均的 3 倍作为最低储值卡面额。</div>
        </el-form-item>
        <el-form-item label="储值卡售价" prop="._amount">
          <el-input @change="onChangeAmount" v-model.number="balanceForm._amount" placeholder="请输入" style="width: 240px;">
            <template slot="prepend">售价</template>
            <template slot="append">元</template>
          </el-input>
          <div class="hui-color-text-secondary hui-font-size-small">售价需小于等于面额，2 位小数以内。面额和售价的关系，可以理解成手机充话费，100 元充值卡，售价 99 元。</div>
        </el-form-item>
        <el-form-item label="续充限制" prop=".reSave">
          <el-radio-group v-model="balanceForm.reSave">
            <el-radio :label="false">不可续充</el-radio>
            <el-radio :label="true">可以续充</el-radio>
          </el-radio-group>
          <ul class="hui-color-text-secondary hui-font-size-small hui-pl-1" style="line-height: 1.5;">
            <li>用户可以购买多张储值卡，每张卡内的金额互不相通</li>
            <li>不可续充的储值卡，用户卡内储值余额消耗完毕后，该张储值卡失效，用户再次充值，会重新发给用户一张新储值卡</li>
            <li>可以续充的储值卡，用户可以反复往该卡内储值，但仅可储值本储值卡的面额，不能充其他的面额</li>
          </ul>
        </el-form-item>
      </h-box>

      <h-box header="其他储值规则（保存后可以修改）">
        <el-form-item label="储值卡标题" prop="title">
          <el-input v-model="balanceForm.title" placeholder="请输入储值卡标题，最多 16 个字" style="width: 400px;"></el-input>
          <div class="hui-color-text-secondary hui-font-size-small">储值卡标题不对消费者展示，仅供管理员备注用</div>
        </el-form-item>
        <el-form-item label="是否礼品卡" prop="isGiftCard">
          <el-radio-group v-model="balanceForm.isGiftCard">
            <el-radio :label="false">非礼品卡</el-radio>
            <el-radio :label="true">礼品卡，可以送人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用门店限制" prop="useAllBranch">
          <el-radio-group v-model="balanceForm.useAllBranch" @change="onChangeUseAllBranch">
            <el-radio :label="true">所有门店参加</el-radio>
            <el-radio :label="false">部分门店参加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可使用门店" prop="canUseBranch" v-if="!balanceForm.useAllBranch">
          <el-table :data="balanceForm.canUseBranch" border stripe size="medium" style="width: 400px; line-height: 23px;" class="hui-mb-1">
            <el-table-column label="门店ID" prop="id"></el-table-column>
            <el-table-column label="门店名称" prop="label"></el-table-column>
          </el-table>
          <el-button @click="handleDialogBranch" type="primary" size="small" icon="el-icon-location" plain>设置活动门店</el-button>
        </el-form-item>
        <el-form-item label="购买储值卡打标签" prop="userTagsBuy">
          <hpro-select-tags :value.sync="balanceForm.userTagsBuy" style="width: 400px;"></hpro-select-tags>
          <div class="hui-color-text-secondary hui-font-size-small">
            <span>给购买过本储值卡的用户打标签，美味建议商户以标签管理用户的行为。</span>
            <router-link to="/home/user/tags/list" target="_blank">新建标签</router-link>
          </div>
        </el-form-item>
        <el-form-item label="领取储值卡打标签" prop="userTagsGet">
          <hpro-select-tags :value.sync="balanceForm.userTagsGet" style="width: 400px;"></hpro-select-tags>
          <div class="hui-color-text-secondary hui-font-size-small">
            <span>给领取过本储值卡的用户打标签，礼品卡的购买人和领取人不同，在此处可灵活设定。</span>
            <router-link to="/home/user/tags/list" target="_blank">新建标签</router-link>
          </div>
        </el-form-item>
      </h-box>

      <h-box header="储值奖励（保存后可以修改）">
        <el-form-item label="赠送会员卡" prop="presentCard">
          <hpro-select-card v-model="balanceForm.presentCard"></hpro-select-card>
          <ul class="hui-color-text-secondary hui-font-size-small hui-pl-1" style="line-height: 1.5;">
            <li>赠送会员卡会赠送给领取会员卡的用户</li>
            <li>如果设置的是“全部门店可用的会员卡”，只有用户持有的会员卡等级小于该赠送会员卡时，才会赠送；如户已经有该等级会员卡，不会重复赠送。如用户的会员卡等级比赠送的高，不会赠送。</li>
            <li>如果设置的是“部分门店可用的会员卡”，无论用户之前是否已经有该张会员卡，均会重新赠送一张。如该会员卡是可售卖的会员卡，用户也无需额外付费。</li>
            <li>充值赠送会员卡，是消费者认可度很高的营销活动类型，建议商户运用好赠送会员卡功能</li>
          </ul>
        </el-form-item>
        <el-form-item label="其他奖励" prop="type">
          <el-radio-group v-model="balanceForm.type" @change="onChangeType">
            <el-radio label="no">无奖励</el-radio>
            <el-radio label="coupon">送优惠券</el-radio>
            <el-radio label="lucky">送红包</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="奖励内容" prop="reward" v-if="balanceForm.type !== 'no'">
          <el-table v-model="balanceForm.reward" :data="balanceForm.reward" stripe border size="medium" style="width: 400px; line-height: 23px;">
            <el-table-column label="优惠券/红包" prop="title"></el-table-column>
            <el-table-column label="数量" prop="number"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="handleDelete(scope.$index, scope.row)" type="danger" size="mini" plain>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="hui-color-text-secondary hui-font-size-small">建议：储值奖励赠送内容的门店适用限制与储值卡适用门店限制相同。</div>
          <el-button v-if="balanceForm.type === 'coupon'" @click="handleDialogReward" :disabled="balanceForm.reward.length >= 5" type="primary" size="mini" icon="el-icon-plus" plain>添加优惠券</el-button>
          <el-button v-if="balanceForm.type === 'lucky'" @click="handleDialogReward" :disabled="balanceForm.reward.length >= 5" type="success" size="mini" icon="el-icon-plus" plain>添加红包</el-button>
        </el-form-item>
      </h-box>

      <h-box>
        <el-form-item label="" slot="footer" class="hui-mb-0">
          <el-button @click="handleSubmit('balanceForm')" :loading="loading" type="primary">{{ type === 'edit' ? '保存' : '创建' }}</el-button>
          <el-button @click="handleBack">返回</el-button>
        </el-form-item>
      </h-box>
    </el-form>

    <hpro-dialog-reward :visible.sync="dialogVisibleReward" v-model="balanceForm.reward" number-ctrl :type="balanceForm.type"></hpro-dialog-reward>
    <hpro-dialog-branch :visible.sync="dialogVisibleBranch" v-model="balanceForm.canUseBranch"></hpro-dialog-branch>
  </div>
</template>

<script>
export default {
  data () {
    return {
      type: '',
      loading: false,
      dialogVisibleReward: false,
      dialogVisibleBranch: false,
      balanceForm: {
        balance: undefined,
        _balance: undefined,
        amount: undefined,
        _amount: undefined,
        reSave: false,
        title: '',
        presentCard: {
          cardId: '',
          title: ''
        },
        type: 'coupon',
        reward: [],
        isGiftCard: false,
        useAllBranch: true,
        canUseBranch: [],
        userTagsBuy: [],
        userTagsGet: []
      },
      balanceFormRoles: {
        _balance: [
          {
            type: 'number',
            required: true,
            min: 0.01,
            message: '储值卡面额必填，数字格式',
            trigger: 'blur, change'
          },
          {
            validator: this.$validateAmount,
            trigger: 'blur'
          }
        ],
        _amount: [
          {
            type: 'number',
            required: true,
            min: 0.01,
            message: '储值卡售价必填',
            trigger: 'blur, change'
          },
          {
            validator: this.$validateAmount,
            trigger: 'blur'
          }
        ],
        reSave: [
          {
            type: 'boolean',
            required: true,
            message: '必选',
            trigger: 'change'
          }
        ],
        title: [
          {
            required: true,
            max: 9,
            message: '储值卡标题必填，最多 9 个字，建议简单直接',
            trigger: 'blur'
          }
        ],
        isGiftCard: [
          {
            type: 'boolean',
            required: true,
            message: '必选',
            trigger: 'change'
          }
        ],
        useAllBranch: [
          {
            required: true,
            type: 'boolean',
            message: '必选',
            trigger: 'change'
          }
        ],
        canUseBranch: [
          {
            required: true,
            type: 'array',
            message: '请至少选择 1 个可参与活动的门店',
            trigger: 'change'
          }
        ],
        userTagsBuy: [
          {
            type: 'array',
            message: '格式必须是array',
            trigger: 'change'
          }
        ],
        userTagsGet: [
          {
            type: 'array',
            message: '格式必须是array',
            trigger: 'change'
          }
        ],
        presentCard: [
          {
            type: 'object',
            message: '数据类型错误，必须为object',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '奖励类型必填',
            trigger: 'change'
          }
        ],
        reward: [
          {
            type: 'array',
            message: '类型为array',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // 面额change
    onChangeBalance () {
      const _balance = this.balanceForm._balance
      if (_balance !== undefined) {
        this.balanceForm.balance = _balance * 100
      }
    },
    // 售价change
    onChangeAmount () {
      const _amount = this.balanceForm._amount
      if (_amount !== undefined) {
        this.balanceForm.amount = _amount * 100
      }
    },
    // 奖励类型变化事件
    onChangeType () {
      this.balanceForm.reward = []
    },

    // 打开红包优惠券选择模态框
    handleDialogReward () {
      this.dialogVisibleReward = true
    },

    // 删除已选择的优惠券或红包事件
    handleDelete (index, row) {
      let reward = this.balanceForm.reward
      reward.splice(index, 1)
      this.balanceForm.reward = reward
    },

    // 设置参加活动门店为空
    onChangeUseAllBranch () {
      if (this.balanceForm.useAllBranch) {
        this.balanceForm.canUseBranch = []
      }
    },

    // 打开选择门店模态框
    handleDialogBranch () {
      this.dialogVisibleBranch = true
    },

    // 返回
    handleBack () {
      this.$router.back()
    },

    // 表单校验
    handleSubmit (formName) {
      this.$formSubmit(formName).then(() => {
        console.log('提交！')
        this.$loading()
        this.loading = true
        setTimeout(() => {
          this.$message({
            message: '储值规则保存成功！',
            type: 'success'
          })
          this.handleBack()
          this.$loading().close()
        }, 1000)
      }).catch(() => {
        console.log('表单校验失败！')
        this.$message({
          message: '必要的信息没填写完整, 请检查!',
          type: 'warning'
        })
        this.loading = false
      })
    }
  },
  created () {}
}
</script>
